//
//  MyCenterViewController.m
//  AllFamily
//
//  Created by chirui on 2018/5/23.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "MyCenterViewController.h"
#import "ChangeUserMessageViewController.h"
#import "AddressListViewController.h"
#import "MySettingViewController.h"
#import "MessageListViewController.h"
#import "CartViewController.h"
#import "MyShareListViewController.h"
#import "MySingleViewController.h"
#import "MyMoneyBageViewController.h"
#import "MyFruitOrderListViewController.h" // 我的订单

@interface MyCenterViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    NSDictionary * userDic;
     UITableView * _tableView;
    NSString * messageCount;
    NSDictionary * shareDic;
    
      UIView * shareBgView;
}

@end

@implementation MyCenterViewController

-(void)viewWillDisappear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden =NO;
    
}

-(void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden = YES; //隐藏
    self.tabBarController.tabBar.hidden = NO;

    if (verifTokenAndEnter) {
       
        [self getUserMessageRequest];
        [self getMessageCount];
        [self getShareData];
//        [self getMessageCountRequest];
//        [self getOrderCountRequest];
    }else {
        userDic = nil;
    }
}


-(void)shareBtnClick{
    if (shareDic) {
        
        UIWindow *window = [[UIApplication sharedApplication].delegate window];
        
        shareBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
        shareBgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        [window addSubview:shareBgView];
        
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(60, HEIGHT/2-70, WIDTH - 120, 140)];
        bgView.backgroundColor = [UIColor whiteColor];
        bgView.layer.cornerRadius = 8.f;
        bgView.layer.masksToBounds = YES;
        [shareBgView addSubview:bgView];
        
        UIButton * audioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        audioBtn.frame = CGRectMake((WIDTH-120)/2 - 80, 30, 60, 60);
        
        [audioBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [audioBtn addTarget:self action:@selector(sharewxpyq:) forControlEvents:UIControlEventTouchUpInside];
        [audioBtn setBackgroundImage:ImageName(@"icon_share_friends") forState:UIControlStateNormal];
        [bgView addSubview:audioBtn];
        
        UILabel * audiolabel = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH-120)/2 - 80, 100, 60, 20)];
        audiolabel.textColor = [UIColor blackColor];
        audiolabel.font = [UIFont systemFontOfSize:13];
        audiolabel.text = @"朋友圈";
        audiolabel.textAlignment = NSTextAlignmentCenter;
        [bgView addSubview:audiolabel];
        
        UIButton * vidoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        vidoBtn.frame = CGRectMake((WIDTH-120)/2+20,30, 60, 60);
        [vidoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [vidoBtn addTarget:self action:@selector(sharewx:) forControlEvents:UIControlEventTouchUpInside];
        [vidoBtn setBackgroundImage:ImageName(@"icon_share_wchat") forState:UIControlStateNormal];
        vidoBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [bgView addSubview:vidoBtn];
        
        UILabel * vidolabel = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH-120)/2+20,100, 60, 20)];
        vidolabel.textColor = [UIColor blackColor];
        vidolabel.font = [UIFont systemFontOfSize:13];
        vidolabel.text = @"微信好友";
        vidolabel.textAlignment = NSTextAlignmentCenter;
        [bgView addSubview:vidolabel];
        
        
        UITapGestureRecognizer * reco = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTapChange:)];
        reco.numberOfTapsRequired = 1;
        [shareBgView addGestureRecognizer:reco];
    }else {
        if (verifTokenAndEnter) {
            
            [self getShareData];
        }else {
            
            LoginAndSignUpVC * login = [[LoginAndSignUpVC alloc]init];
            login.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:login animated:YES];
        }
        
    }
    
}

-(void)doTapChange:(UITapGestureRecognizer *)send{
    
    [shareBgView removeFromSuperview];
    
}

-(void)sharewxpyq:(UIButton *)btn{
    [shareBgView removeFromSuperview];
    UIImage *iamge = [UIImage imageNamed:@"img_copy_1"];
    NSData *data = UIImageJPEGRepresentation(iamge, 0.8);
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = shareDic[@"title"];
    message.description = shareDic[@"content"];
    [message setThumbImage:[UIImage imageWithData:data]];
    
    WXWebpageObject *webPageObject = [WXWebpageObject object];
    webPageObject.webpageUrl = shareDic[@"url"];
    message.mediaObject = webPageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;
    [WXApi sendReq:req];
}

-(void)sharewx:(UIButton *)btn{
    [shareBgView removeFromSuperview];
    UIImage *iamge = [UIImage imageNamed:@"img_copy_1"];
    NSData *data = UIImageJPEGRepresentation(iamge, 0.8);
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = shareDic[@"title"];
    message.description = shareDic[@"content"];
    [message setThumbImage:[UIImage imageWithData:data]];
    
    WXWebpageObject *webPageObject = [WXWebpageObject object];
    webPageObject.webpageUrl = shareDic[@"url"];
    message.mediaObject = webPageObject;
    
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    [WXApi sendReq:req];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    messageCount = @"0";
    [self creatTableView];
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, -SH_StatusBarHeight, WIDTH, HEIGHT-SH_StatusBarHeight+SH_TabBarHeight) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        
        return 2;
    }else {
         return 3;
    }
   
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
         return 190;
    }else {
        
        return 10;
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellId = @"cellId";
    
    NSArray * titleArray = @[@[@"我的订单",@"我的钱包"],@[@"销售业绩",@"我要报单",@"购物车"],@[@"我的消息",@"收货地址",@"设置"]];
    NSArray * imageArray;
    
    if ([messageCount isEqualToString:@"0"]) {
        
        imageArray = @[@[@"icon_user_order",@"icon_user_wallet"],@[@"icon_user_share",@"icon_user_declaration",@"icon_user_shopcat"],@[@"icon_user_news",@"icon_user_add",@"icon_user_set"]];
    }else {
        imageArray = @[@[@"icon_user_order",@"icon_user_wallet"],@[@"icon_user_share",@"icon_user_declaration",@"icon_user_shopcat"],@[@"icon_user_news_pre",@"icon_user_add",@"icon_user_set"]];
        
    }
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:cellId ];
    if (cell==nil) {
        
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.textLabel.text = titleArray[indexPath.section][indexPath.row];
    cell.imageView.image = ImageName(imageArray[indexPath.section][indexPath.row]);
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section==0) {
        

    UIView * heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 190)];
    heardView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UIImageView * bgImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 190)];
    bgImage.userInteractionEnabled = YES;
    bgImage.image = ImageName(@"img_user_bg");
    [heardView addSubview:bgImage];
    
    UIButton * userIconBtn = [self btnFrame:CGRectMake(10, 90, 60, 60) andImageName:@"img_user_initial _head" andSEL:@selector(photoClick) onView:bgImage];
    userIconBtn.layer.cornerRadius = 30.f;
    userIconBtn.layer.masksToBounds = YES;
    
    UILabel * userNameLabel =[[UILabel alloc]initWithFrame:CGRectMake(80, 95, 200, 20)];
    userNameLabel.font =[UIFont systemFontOfSize:16];
    userNameLabel.textColor =[UIColor whiteColor];
    userNameLabel.text = @"未登录";
    userNameLabel.numberOfLines = 1;
    [userNameLabel sizeToFit];
    [bgImage addSubview:userNameLabel];
        
        UIButton * shareBtn = [self btnFrame:CGRectMake(WIDTH -40, 17, 35, 35) andImageName:@"icon_user_shareRight" andSEL:@selector(shareBtnClick) onView:bgImage];
    

    UILabel *tagLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(userNameLabel.frame)+5, CGRectGetMinY(userNameLabel.frame), 100, 20)];
    tagLabel.font = [UIFont systemFontOfSize:14];
    tagLabel.textColor = [UIColor whiteColor];


    [bgImage addSubview:tagLabel];
    
    UILabel *bageTagLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, CGRectGetMaxY(userNameLabel.frame)+10, 65, 20)];
    bageTagLabel.font = [UIFont systemFontOfSize:13];
    bageTagLabel.textColor = [UIColor whiteColor];
        bageTagLabel.textAlignment = NSTextAlignmentCenter;
    bageTagLabel.backgroundColor = Color(58, 168, 38);
    bageTagLabel.hidden = YES;
    bageTagLabel.text = @"购车基金";
    bageTagLabel.layer.cornerRadius = 10;
    bageTagLabel.layer.masksToBounds = YES;
    [bgImage addSubview:bageTagLabel];
        
       
        
        if (userDic) {
            if ([userDic[@"mem_level"] isEqualToString:@"normal"]) {
                tagLabel.text= @"";
            }else if ([userDic[@"mem_level"] isEqualToString:@"sale"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[经销商]";
                
            }else if ([userDic[@"mem_level"] isEqualToString:@"star"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[星级经销商]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"service"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[服务站]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"run"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[区县代理]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"city"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[市代理]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"province"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[省代理]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"area"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[大区经理]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"manager"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[大区总监+2%分红]";
            }else if ([userDic[@"mem_level"] isEqualToString:@"officer"]){
                bageTagLabel.hidden = NO;
                tagLabel.text= @"[参与分红]";
            }
            
            [userIconBtn sd_setBackgroundImageWithURL:ImageUrl(userDic[@"header"]) forState:UIControlStateNormal placeholderImage:ImageName(@"img_user_initial _head")] ;
            NSString * name = userDic[@"nickname"];
            if (name ==nil||name.length<=0 ) {
                name = @"未设置";
            }
            userNameLabel.text = name;
            userNameLabel.numberOfLines = 1;
            [userNameLabel sizeToFit];
            tagLabel.frame = CGRectMake(CGRectGetMaxX(userNameLabel.frame)+5, CGRectGetMinY(userNameLabel.frame), 100, 20);
        }else {
             bageTagLabel.hidden = YES;
             tagLabel.hidden = YES;
        }

    return heardView;
    }else {
        return nil;
    }
}



-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (verifTokenAndEnter) {
        
    
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            
            MyFruitOrderListViewController * order = [[MyFruitOrderListViewController alloc]init];
            order.hidesBottomBarWhenPushed = YES;
            order.index = 0;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:order animated:YES];
        }
        if (indexPath.row==1) {
            
            MyMoneyBageViewController * money = [[MyMoneyBageViewController alloc]init];
            money.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:money animated:YES];
        }
    }
    
    if (indexPath.section==1) {
        if (indexPath.row==0) {
            MyShareListViewController * share = [[MyShareListViewController alloc]init];
            share.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:share animated:YES];
        }
        if (indexPath.row==1) {
            if ([userDic[@"mem_level"] isEqualToString:@"service"]) {
                MySingleViewController * share = [[MySingleViewController alloc]init];
                share.hidesBottomBarWhenPushed = YES;
                self.navigationController.navigationBar.translucent = NO;
                [self.navigationController pushViewController:share animated:YES];
            }else{
                SHuiMBhudTextTimeStr(@"您还没有权限！");
            }
           
        }
        if (indexPath.row==2) {
            CartViewController * cart = [[CartViewController alloc]init];
            cart.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:cart animated:YES];
        }
    }
    if (indexPath.section==2) {
        if (indexPath.row==0) {
            MessageListViewController * message = [[MessageListViewController alloc]init];
            message.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:message animated:YES];
        }else if (indexPath.row==1){
            AddressListViewController * address = [[AddressListViewController alloc]init];
            address.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:address animated:YES];
        }else{
            MySettingViewController * set = [[MySettingViewController alloc]init];
            set.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:set animated:YES];
            
        }
    }
    }else {
        
        LoginAndSignUpVC * login = [[LoginAndSignUpVC alloc]init];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
    }
}

-(void)getUserMessageRequest{

    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token")};

    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_userMessage_api) andparameters:dic Success:^(id responseObject) {

        if (codeSucess) {

            userDic = responseObject[@"datas"];

        }else {

            if ([responseObject[@"code"] intValue]==220) {

                USER_DEFAULTSet(@"", @"token");
                USER_DEFAULTSet(@"no", @"enter");
                USER_DEFAULTSet(@"no", @"tokenVerify");
                USER_DEFAULTSet(@"", @"mid");
                userDic = nil;
            }

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

        [_tableView reloadData];

    } failed:^(NSError *error) {

        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];

}

-(void)getMessageCount{
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token")};
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(noRead_messageCount_api) andparameters:dic Success:^(id responseObject) {
        
        if (codeSucess) {
            
            messageCount = responseObject[@"datas"][@"count"];
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
        [_tableView reloadData];
        
    } failed:^(NSError *error) {
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];

}

-(void)getShareData{
    NSDictionary * dic = @{
                           @"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token")
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(share_data_api) andparameters:dic Success:^(id responseObject) {
        if (codeSucess) {
            shareDic = responseObject[@"datas"];
        }else {
            shareDic = nil;
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        [_tableView reloadData];
    } failed:^(NSError *error) {
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
}


-(void)photoClick{
    
    if (verifTokenAndEnter) {
    
    ChangeUserMessageViewController * change = [[ChangeUserMessageViewController alloc]init];
    change.hidesBottomBarWhenPushed = YES;
    change.dataDic = userDic;
    
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController pushViewController:change animated:YES];
    }else {
        
        LoginAndSignUpVC * login = [[LoginAndSignUpVC alloc]init];
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
    }
}

-(UIButton *)btnFrame:(CGRect)rec andImageName:(NSString *)imageName andSEL:(SEL)sel onView:(UIView *)view{
    
    UIButton * scanBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    scanBtn.frame = rec;
    [scanBtn setBackgroundImage:ImageName(imageName) forState:UIControlStateNormal];
    [scanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [scanBtn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    scanBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [view addSubview:scanBtn];
    return scanBtn;
    
}

@end
